<template>
  <div>
    <page-dialog
      :title="addAmortizationInfo.title"
      v-model:visible="shows"
      :width="addAmortizationInfo.width"
      :bt-list="addAmortizationInfo.btList"
    >
      <el-form
        ref="assetAmortizationDeptTableForm"
        :model="assetAmortizationDeptTableInfo"
      >
        <DialogTable
          :data="assetAmortizationDeptTableInfo.data"
          :pager="false"
          :check-box="false"
          :tab-index="true"
          :field-list="assetAmortizationDeptTableInfo.fieldList"
          :handle="assetAmortizationDeptTableInfo.handle"
        >
          <template v-slot:col-useDeptName="scope">
            <el-form-item
              :prop="`data.${scope.$index}.useDeptName`"
              :rules="[
                {
                  required: scope.$index >= 0,
                  message: '请选择使用部门',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model="scope.row.useDeptName"
                style="width: 100%; margintop: 18px"
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择使用部门"
              >
                <template v-if="scope.$index > 0" #append>
                  <el-icon @click="openAmortizationDept(scope.$index)"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </template>
          <template v-slot:col-rate="scope">
            <el-form-item
              :prop="`data.${scope.$index}.rate`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.positiveScore,
                        trigger: ['blur'],
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                v-model.lazy="scope.row.rate"
                style="width: 100%; margintop: 18px"
                clearable
                controls-position="right"
                :min="0"
                :max="100"
                :precision="2"
              />
            </el-form-item>
          </template>
        </DialogTable>
      </el-form>
    </page-dialog>
    <select-dept
      v-if="addAssetAmortizationDeptInfo.visible"
      v-model:show-dialog="addAssetAmortizationDeptInfo.visible"
      :query="addAssetAmortizationDeptInfo.query"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectAssetAmortizationDeptCallback"
    />
  </div>
</template>
<script setup name="Amortization">
import PageDialog from '../PageDialog/index'
import DialogTable from '../DialogTable/index'
import SelectDept from '@/components/SelectDept/index'

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false,
  },
  list: {
    type: Array,
    default: function () {
      return []
    },
  },
})
const { proxy } = getCurrentInstance()
const emit = defineEmits(['update', 'callback'])
const changeAmortizationDeptNameFlag = ref(false)
const assetAmortizationDeptTableInfo = reactive({
  data: props.list.length
    ? proxy.$fn.deepClone(props.list)
    : [{ useDeptName: '', rate: 0 }],
  fieldList: [
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'slot',
    },
    {
      label: '占比',
      value: 'rate',
      type: 'slot',
      labelTip: '总值100%',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '新增行',
        event: addDept,
        show: true,
      },
      {
        label: '删除',
        event: removeDept,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: ifRenderRemoveDept,
      },
    ],
  },
})

const addAssetAmortizationDeptInfo = reactive({
  visible: false,
  index: '',
  query: {
    deptAuth: 'id',
    idNotIn: '',
  },
})
const addAmortizationInfo = reactive({
  visible: false,
  title: '添加使用部门',
  width: '60%',
  row: {},
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeAmortization,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveAmortization,
      saveLoading: false,
      show: true,
    },
  ],
})

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})

function closeAmortization() {
  //关闭使用部门弹窗
  assetAmortizationDeptTableInfo.data = [{ useDeptName: '', rate: 0 }]
  shows.value = false
}
function saveAmortization() {
  //保存使用部门
  proxy.$refs['assetAmortizationDeptTableForm'].validate((valid) => {
    if (valid) {
      let sumQty = 0
      assetAmortizationDeptTableInfo.data.forEach((item) => {
        sumQty = proxy.$fn.accAdd(item.rate || 0, sumQty)
      })
      if (sumQty !== 100) {
        proxy.$message({
          showClose: true,
          message: `添加的使用部门占比之和必须等于100`,
          type: 'warning',
          duration: 3500,
        })
        return
      }
      emit(
        'callback',
        assetAmortizationDeptTableInfo.data,
        changeAmortizationDeptNameFlag.value
      )
      closeAmortization()
    }
  })
}
function openAmortizationDept(index) {
  //新增使用部门
  let ids = []
  if (
    assetAmortizationDeptTableInfo.data &&
    assetAmortizationDeptTableInfo.data.length
  ) {
    assetAmortizationDeptTableInfo.data.forEach((item) => {
      if (item.useDeptName) {
        ids.push(item.useDeptId)
      }
    })
  }
  addAssetAmortizationDeptInfo.query.idNotIn = ids.toString()
  addAssetAmortizationDeptInfo.index = index
  addAssetAmortizationDeptInfo.visible = true
}
function selectAssetAmortizationDeptCallback(data) {
  changeAmortizationDeptNameFlag.value = true
  //选择使用部门返回
  let currIndex = addAssetAmortizationDeptInfo.index
  if (data && data.id) {
    assetAmortizationDeptTableInfo.data.forEach((item, index) => {
      if (index === currIndex) {
        item['useDeptName'] = data.name
        item['useDeptId'] = data.id
      }
    })
  } else {
    assetAmortizationDeptTableInfo.data.forEach((item, index) => {
      if (index === currIndex) item['useDeptName'] = ''
      item['useDeptId'] = -2
    })
  }
  addAssetAmortizationDeptInfo.visible = false
}
function addDept() {
  //添加使用部门
  assetAmortizationDeptTableInfo.data.push({
    useDeptName: '',
    rate: 0,
  })
}
function removeDept(row) {
  //删除使用部门
  assetAmortizationDeptTableInfo.data =
    assetAmortizationDeptTableInfo.data.filter((item) => item !== row)
  setTimeout(() => {
    proxy.$refs.assetAmortizationDeptTableForm.clearValidate()
  }, 30)
}
function ifRenderRemoveDept(row, index) {
  if (index === 0) return false
  //使用部门列表是否显示删除
  if (assetAmortizationDeptTableInfo.data.length - 1) {
    return true
  } else {
    return false
  }
}
</script>
